<template>
  <div class="email-modal">
    <div v-if="loading" class="loading">
      <text>加载中...</text>
    </div>
    <div v-else-if="emails.length === 0" class="empty">
      <text>暂无邮件</text>
    </div>
    <div v-else class="email-list">
      <div 
        v-for="email in emails" 
        :key="email.id || email._id"
        class="email-item"
        :class="{ unread: email.read === 0 }"
        @click="selectEmail(email)"
      >
        <div class="email-header">
          <span class="email-sender">{{ email.name || '系统' }}</span>
          <span class="email-time">{{ formatTime(email.created_at || email.createdAt) }}</span>
        </div>
        <div class="email-title">{{ email.title || email.Title || '无标题' }}</div>
        <div class="email-actions">
          <button 
            v-if="email.read === 0 && email.reward && Object.keys(email.reward).length > 0"
            class="reward-btn"
            @click.stop="claimReward(email)"
            :disabled="claiming"
          >
            {{ claiming ? '领取中...' : '领取奖励' }}
          </button>
          <button 
            class="delete-btn"
            @click.stop="deleteEmail(email)"
            :disabled="deleting"
          >
            删除
          </button>
        </div>
      </div>
    </div>
    <div v-if="emails.length > 0" class="email-actions-footer">
      <button 
        class="claim-all-btn"
        @click="claimAllRewards"
        :disabled="claimingAll || !hasUnreadRewards"
      >
        {{ claimingAll ? '领取中...' : '一键领取' }}
      </button>
    </div>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'EmailModal',
  data() {
    return {
      emails: [],
      loading: true,
      claiming: false,
      claimingAll: false,
      deleting: false
    }
  },
  computed: {
    hasUnreadRewards() {
      return this.emails.some(email => 
        email.read === 0 && email.reward && Object.keys(email.reward).length > 0
      )
    }
  },
  mounted() {
    this.loadEmails()
  },
  methods: {
    async loadEmails() {
      this.loading = true
      try {
        const response = await api.post('/email/info', {})
        if (response && response.code === 1) {
          this.emails = Array.isArray(response.data) ? response.data : []
        } else {
          uni.showToast({ title: response?.msg || '加载失败', icon: 'none' })
        }
      } catch (error) {
        console.error('加载邮件失败:', error)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        this.loading = false
      }
    },
    
    async claimReward(email) {
      if (this.claiming || email.read === 1) return
      
      this.claiming = true
      try {
        const response = await api.post('/email/reward', { id: email.id || email._id })
        if (response && response.code === 1) {
          uni.showToast({ title: '领取成功', icon: 'success' })
          email.read = 1
          // 触发父组件更新徽章
          this.$emit('updated')
          this.loadEmails()
        } else {
          uni.showToast({ title: response?.msg || '领取失败', icon: 'none' })
        }
      } catch (error) {
        console.error('领取奖励失败:', error)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        this.claiming = false
      }
    },
    
    async claimAllRewards() {
      if (this.claimingAll || !this.hasUnreadRewards) return
      
      this.claimingAll = true
      try {
        const response = await api.post('/email/reward_all', {})
        if (response && response.code === 1) {
          uni.showToast({ title: '一键领取成功', icon: 'success' })
          this.$emit('updated')
          this.loadEmails()
        } else {
          uni.showToast({ title: response?.msg || '领取失败', icon: 'none' })
        }
      } catch (error) {
        console.error('一键领取失败:', error)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        this.claimingAll = false
      }
    },
    
    async deleteEmail(email) {
      if (this.deleting) return
      
      const confirmed = await new Promise(resolve => {
        uni.showModal({
          title: '确认删除',
          content: '确定要删除这封邮件吗？',
          success: (res) => resolve(res.confirm),
          fail: () => resolve(false)
        })
      })
      
      if (!confirmed) return
      
      this.deleting = true
      try {
        const response = await api.post('/email/delete_email', { 
          ids: [email.id || email._id] 
        })
        if (response && response.code === 1) {
          uni.showToast({ title: '删除成功', icon: 'success' })
          this.$emit('updated')
          this.loadEmails()
        } else {
          uni.showToast({ title: response?.msg || '删除失败', icon: 'none' })
        }
      } catch (error) {
        console.error('删除邮件失败:', error)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        this.deleting = false
      }
    },
    
    selectEmail(email) {
      // 可以扩展：点击查看邮件详情
      console.log('查看邮件:', email)
    },
    
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
          const minutes = Math.floor(diff / (1000 * 60))
          return minutes === 0 ? '刚刚' : `${minutes}分钟前`
        }
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return date.toLocaleDateString('zh-CN')
      }
    }
  }
}
</script>

<style scoped>
.email-modal {
  max-height: 60vh;
  overflow-y: auto;
}

.loading, .empty {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.email-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.email-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #ddd;
  transition: all 0.3s ease;
}

.email-item.unread {
  background: #e3f2fd;
  border-left-color: #1890ff;
}

.email-item:hover {
  background: #f0f0f0;
}

.email-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.email-sender {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.email-time {
  font-size: 12px;
  color: #999;
}

.email-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.email-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.reward-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.reward-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.reward-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.delete-btn {
  background: #f0f0f0;
  color: #666;
}

.delete-btn:hover:not(:disabled) {
  background: #e0e0e0;
}

.reward-btn:disabled, .delete-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.email-actions-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  text-align: center;
}

.claim-all-btn {
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.claim-all-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.claim-all-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

